/*
Copyright (c) 2010, Advanced Micro Devices
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:

Redistributions of source code must retain the above copyright notice, this list of conditions 
and the following disclaimer.

Redistributions in binary form must reproduce the above copyright notice, this list of 
conditions and the following disclaimer in the documentation and/or other materials provided 
with the distribution.

Neither the name of Advanced Micro Devices nor the names of its contributors may be used to endorse 
or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY 
AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR 
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

#include <QtGui>
#include <QDebug>

#include "Stage.h"
#include "StagePropertiesDialog.h"
#include "EditorWindow.h"

Stage::Stage( EditorView * view, EditorWindow * window ) 
: Node::Node( view, window )
{
	myTextColor = Qt::darkGreen;
	myOutlineColor = Qt::darkBlue;
	myBackgroundColor = Qt::yellow;

	kernelIs( NULL );
	globalDimensionsIs( 0 );
	localDimensionsIs( 0 );
	barrierIs( "" );

	setFlags(ItemIsMovable | ItemIsSelectable);
}

Stage::~Stage()
{
	foreach (Link *link, myLinks)
		delete link;
	window()->stages().remove( name() );
}

#if 0
QRectF Stage::outlineRect() const
{
	const int Padding = 8;
	QFontMetricsF metrics = qApp->font();
	QRectF rect = metrics.boundingRect(myText);
	qreal width = rect.width();
	QRectF kernelRect = rect;
	if( kernel() != NULL ){
		kernelRect = metrics.boundingRect( kernel()->text() );
		if( kernelRect.width() > width ){
			width = kernelRect.width();
		}
	}
	rect.setWidth( width );
	//rect.setHeight( 2 * rect.height() + Padding );
	rect.adjust(-Padding, -Padding, +Padding, +Padding);
	rect.translate(-rect.center());
	return rect;	
}


QPainterPath Stage::shape() const
{
	// to do the shape must be large enough to accomodate all of the inputs and outputs
	QRectF rect = outlineRect();
	rect.setHeight( rect.width() );

	QPainterPath path;
#if 0
	path.addRoundRect(rect, roundness(rect.width()),
		roundness(rect.height()));
#else
	path.addEllipse( rect );
#endif
	return path;
}
#endif

void Stage::formatText() 
{
	if( kernel() != NULL ){
		setText( tr( "%1:%2" ).arg( name() ).arg( kernel()->name() ));
	}
	else{
		setText( name() );
	}
}

void Stage::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event)
{
	propertiesDialog();
}

void Stage::propertiesDialog()
{
	StagePropertiesDialog dialog( this, window(), view() );
	dialog.exec();
}

void Stage::kernelNameIs( QString kernelName )
{
	Kernel * kernel = window()->kernels().find( kernelName ).value();
	kernelIs( kernel );
}


void Stage::writeXml( QXmlStreamWriter & xmlsw ) const
{
	xmlsw.writeStartElement( "stage" );
	Node::writeXml( xmlsw );
	xmlsw.writeTextElement( "type", type_() );
	if( kernel() != NULL ){
		xmlsw.writeTextElement( "kernel", kernel()->name() );
		for( int i = 0; i < mArguments.size(); ++i ){
			xmlsw.writeStartElement( "argument" );
			xmlsw.writeTextElement( "argumentName", mArguments[ i ] );
			xmlsw.writeEndElement();
		}//for
	}
	else{
		xmlsw.writeTextElement( "kernel", "" );
	}
	xmlsw.writeEndElement();
}

void Stage::readXml( QXmlStreamReader & xmlsr ) 
{
	int idx = -1;
	while( !xmlsr.atEnd() ){
		QXmlStreamReader::TokenType tokenType = xmlsr.readNext();
		if( tokenType == QXmlStreamReader::StartElement ){
			if( xmlsr.name() == "node" ){
				Node::readXml( xmlsr );
			}
			else if( xmlsr.name() == "argument" ){
				idx++;
			}
			else if( xmlsr.name() == "type" ){
				typeIs( xmlsr.readElementText() );
			}
			else if( xmlsr.name() == "kernel" ){
				QString kernelName = xmlsr.readElementText();
				Kernels::iterator kIt = window()->kernels().find( kernelName );
				if( kIt != window()->kernels().end() ){
					Kernel * kernel = kIt.value();
					kernelIs( kernel );
				}
			}
			else if( xmlsr.name() == "argumentName" ){
				mArguments.insert( idx, xmlsr.readElementText() );
			}
		}
		else if( tokenType == QXmlStreamReader::EndElement ){
			if( xmlsr.name() == "stage" ){
				break;
			}
		}
	}// while
}

void Stage::build( std::ofstream & file )
{
	file << "Stage " << name().toStdString() << " : ";
	if( kernel() == NULL ){
		file << "null (";
	}
	else{
		file << kernel()->name().toStdString() << "(" << std::endl;
		// new kernel signature
		bool first = true;
		for( int i = 1; i <= kernel()->numParameters(); ++i ){
			if( !first ){
				file << "," << std::endl;
			}
			first = false;
			file << mArguments[ i - 1 ].toStdString();
		}//for
	}
	file << std::endl << "){" << std::endl;
	if( type_() == "host" ){
		file << "external=1;" << std::endl;
	}
	if( type_() == "selector" ){
		file << "branchSelector=" << selectorCount() << ";" << std::endl;
	}
	if( type_() == "barrier" ){
		if( barrier().compare( "" ) ){
			file << "barrier=" << barrier().toStdString() << ";" << std::endl;
		}
	}
	if( globalDimensions() > 0 ){
		file << "globalDimensions=" << globalDimensions() << ";" << std::endl;
	}
	if( globalRange().compare( "" ) != 0 ){
		file << "globalRange=" << globalRange().toStdString() << ";" << std::endl;
	}
	if( localDimensions() > 0 ){
		file << "localDimensions=" << localDimensions() << ";" << std::endl;
	}
	if( localRange().compare( "" ) != 0 ){
		file << "localRange=" << localRange().toStdString() << ";" << std::endl;
	}
	file << "}" << std::endl;
}

